package com.mz.mattress.client.service.impl;

import com.mz.mattress.api.common.Constants;
import com.mz.mattress.api.entity.MemberBalanceRecord;
import com.mz.mattress.api.entity.MemberMer;
import com.mz.mattress.api.entity.OrderUseTimesBonus;
import com.mz.mattress.client.mapper.MemberBalanceRecordMapper;
import com.mz.mattress.client.mapper.MemberMerMapper;
import com.mz.mattress.client.mapper.OrderUseTimesBonusMapper;
import com.mz.mattress.client.service.MemberMerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.mz.mattress.api.common.Constants.SYS_MEMBER_ID;

@Slf4j
@Service
public class MemberMerServiceImpl implements MemberMerService {

    @Autowired
    private MemberMerMapper memberMerMapper;

    @Autowired
    private MemberBalanceRecordMapper memberBalanceRecordMapper;

    @Autowired
    private OrderUseTimesBonusMapper orderUseTimesBonusMapper;

    @Override
    public void genSysMember() {

        MemberMer memberMer = memberMerMapper.selectById(SYS_MEMBER_ID);

        if (memberMer == null) {
            memberMer = new MemberMer();
            memberMer.setId(SYS_MEMBER_ID);
            memberMer.setName("平台");
            memberMer.setNickname("平台");
            memberMer.setType(Constants.ROLE_SYS);
            memberMer.setBalance(0);
            memberMer.setSumCashOut(0);
            memberMer.setSumIncome(0);
            memberMer.setStatus(0);
            memberMer.setChainShop(0);
            memberMerMapper.insert(memberMer);
        }

    }

    @Override
    public void sendBonus(Long memberId, Integer bonus, Long orderId, Integer recordId, Integer bonusId) {

        if (memberId == null || bonus == null) {
            return;
        }

        log.info("doSendBonusToMember,memberId={},bonus={},orderId={},recordId={}", memberId, bonus, orderId, recordId);

        Integer balance = memberMerMapper.lockMember(memberId);
        if (balance == null) {
            log.error("not_find_member,memberId=" + memberId);
            return;
        }

        memberMerMapper.addBalance(memberId, bonus);

        MemberBalanceRecord record = new MemberBalanceRecord();
        record.setMemberId(memberId);
        record.setBalance(balance);
        record.setChanges(bonus);
        record.setAfters(balance + bonus);
        record.setOrderId(orderId.toString());
        record.setRecordId(recordId);
        record.setRemark("发放佣金");
        memberBalanceRecordMapper.insert(record);

        if (bonusId != null) {

            //标记已发放
            OrderUseTimesBonus update = new OrderUseTimesBonus();
            update.setId(bonusId);
            update.setDone(1);
            orderUseTimesBonusMapper.updateById(update);

        }

    }

}
